﻿

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Enums;
using XT.Common.Interfaces;
using XT.Common.Models.SignalR;
using XT.Common.Services;

namespace IotClientService;
public class LogService : ILogService
{
    public event EventHandler<string> AddLogEvent;

    private readonly ILog log = null;
    private readonly ILog logError = null;
    private readonly ILog logHeart = null;
    private readonly ISignalRService _signalRService;
    public LogService(ISignalRService signalRService)
    {
        log = log4net.LogManager.GetLogger("loginfo");
        logError = log4net.LogManager.GetLogger("logerror");
        logHeart= log4net.LogManager.GetLogger("logheart");
        _signalRService = signalRService;
    }
    public void Log(string info)
    {
        log.Info(info);
        WriteConsole(info);
    }

    public void LogError(string info, Exception ex)
    {
        logError.Error(info, ex);
        WriteConsole(info, ex);
    }

    public void LogError(string error)
    {
        logError.Error(error);
        WriteConsole(error);
    }

    public void LogHeart(string info)
    {
        if (info.Contains("Error") || info.Contains("error"))
        {
            logHeart.Error(info);
        }
        else
        logHeart.Info(info);
        WriteConsole(info);
    }

    public async Task LogRemote(RemoteLog remoteLog)
    {
         WriteConsole($"{remoteLog.Title} {remoteLog.Content}");

        try
        {
            if (remoteLog.Type == LogEnum.Error)
            {
                logError.Error($"{remoteLog.ID} Title {remoteLog.Title},Content:{remoteLog.Content}");
            }
            else
            {
                log.Info($"{remoteLog.ID} Title {remoteLog.Title},Content:{remoteLog.Content}");
            }
          
            if (!_signalRService.IsConnected) return;
            await _signalRService.WriteLog(remoteLog);
        }
        catch (Exception ex)
        {
            WriteConsole($"{remoteLog.ID} {remoteLog.Title} {remoteLog.Content}",ex);
        }
        return;
    }

    private void WriteConsole(string msg,Exception ex=null)
    {
        var log =$"{DateTime.Now} {msg} {ex?.StackTrace}";
        Console.WriteLine(log);
    }
}
